/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dopdf.io;

import org.dopdf.document.hash.strategy.DocumentHashingStrategyDelegate;
import org.dopdf.document.model.DocumentDetail;
import org.dopdf.document.model.ResourceDetail;
import org.dopdf.document.read.DocumentReader;

import javax.servlet.ServletResponse;

/**
 * The class that is responsible for downloading the document.
 *
 * @author Deep Shah
 */
public class DocumentDownloader {
    /** The document detail reference. */
    private DocumentDetail documentDetail;

    /** The servlet response. */
    private ServletResponse response;

    /**
     * The constructor that takes in the document detail and servlet response as argument.
     * @param documentDetail the document details
     * @param response the servlet response to which the document is to be written.
     */
    public DocumentDownloader(final DocumentDetail documentDetail, final ServletResponse response) {
        this.documentDetail = documentDetail;
        this.response = response;
    }

    /**
     * This method will download the document.  Basically this method will write the document to the output stream.
     */
    public void download() {
        final DocumentReader documentReader = new DocumentHashingStrategyDelegate(
                documentDetail.getDocumentFetchingStrategy()).unHash(documentDetail.getDocumentId());
        final ResourceDetail resourceDetail = documentReader.getDocumentAsResource();
        new ResponseWriter(response).write(resourceDetail);
    }
}
